export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

export function getRandom (n:number, m:number) {
    var num = Math.floor(Math.random() * (m - n + 1) + n)
    return num
}

export function floatInRange(start:number, end: number){
    return start + Math.random()*(end - start)
}

export function getRadiansByAngle(angle:number){
	return Math.PI/180*angle
}

export function isArray(val: any) {
    return Object.prototype.toString.call(val) === "[object Array]";
}

export function isEmpty(val: any) {
    return (
        val === undefined ||
        val === null ||
        (typeof val === "string" && val.length === 0) ||
        (isArray(val) && val.length === 0) ||
        (typeof val === "number" && isNaN(val))
    );
}

export function isDate(val: any) {
    return Object.prototype.toString.call(val) === "[object Date]";
}

export function isNumber(val: any) {
    return Object.prototype.toString.call(val) === "[object Number]";
}

export function parseTime(time:any, cFormat?:string):string {
    if (arguments.length === 0) {
        return '';
    }

    const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (isDate(time)) {
        date = time;
    } else if (isNumber(time)) {
        if (String(time).length === 10) time = parseInt(time) * 1000;
        date = new Date(time);
    } else {
        date = new Date(time);
    }

    const formatObj:any = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };

    //console.log(formatObj,'formatObj')

    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a")
            return ["日","一", "二", "三", "四", "五", "六"][value];
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value || 0;
    });

    return time_str;
}
